﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Web;
using System.Web.UI;

namespace Landscape.Elements
{
    internal class Control
    {
        public string Name;
        public string VirtualPath;
        public Dictionary<string, string> Properties;

        public string ControlId;
        public string PlaceHolderId;
        public List<KeyValuePair<string, string>> Params = new List<KeyValuePair<string, string>>();

        public Control(XmlNode node) {
            XmlNode nameAttributeNode = node.Attributes.GetNamedItem("name");

            if (nameAttributeNode == null || nameAttributeNode.Value.Length == 0)
            {
                throw new Exceptions.XmlNodeException("Missing 'name' attribute.", node);
            }

            Name = nameAttributeNode.Value;
            VirtualPath = Globals.Config.Setting("landscapeUserControlsVDir") + "/" + Name + ".ascx";

            foreach (XmlNode attr in node.Attributes)
            {
                // ignore internal parameters and namespaced attributes
                if (attr.Name != "name" && string.IsNullOrEmpty(attr.NamespaceURI))
                {
                    Params.Add(new KeyValuePair<string, string>(attr.Name, attr.Value));
                }
            }

            ControlId = Renderer.placeholder.UniqueID + "_"+ Name + Renderer.placeholder.Controls.Count.ToString();
            PlaceHolderId = ControlId + "_pholder";

            XmlElement ucPlaceholder = node.OwnerDocument.CreateElement("asp", "placeholder", "remove");
            ucPlaceholder.SetAttribute("id", PlaceHolderId);
            ucPlaceholder.SetAttribute("runat", "server");
            ucPlaceholder.RemoveAttribute("xmlns");

            node.ParentNode.ReplaceChild(ucPlaceholder, node);
            
            // get configurable properties
            UserControl uc = (UserControl)Renderer.placeholder.Page.TemplateControl.LoadControl(VirtualPath);
            Properties = Globals.GetClassProperties(uc.GetType().BaseType, new string[] {
                "System.Int32", "System.Boolean","System.String"
            });
        }
    }
}
